﻿using CCSSolderUI.Models;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;

namespace CCSSolderUI.ViewModels.Dialogs
{
    public class MPLCDialogViewModel : BindableBase, IDialogAware
    {
        #region 变量
        CancellationTokenSource source;
        #endregion
        #region 属性
        private ObservableCollection<bool> pLC_X;
        public ObservableCollection<bool> PLC_X
        {
            get { return pLC_X; }
            set { SetProperty(ref pLC_X, value); }
        }
        #endregion
        #region 导航
        public string Title => "PLC";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            if (source != null)
            {
                source.Cancel();
            }
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            Task.Run(() => UpdateUI(token), token);
        }
        #endregion
        #region 构造函数
        public MPLCDialogViewModel()
        {
            PLC_X = new ObservableCollection<bool>();
            for (int i = 0; i < 16; i++)
            {
                PLC_X.Add(false);
            }
        }
        #endregion
        #region 功能函数
        private void UpdateUI(CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (PLCModbus.Instance.Connected)
                {
                    bool[] xs = PLCModbus.Instance.ReadXCoils(0, 16);
                    for (int i = 0; i < xs.Length && i < PLC_X.Count; i++)
                    {
                        PLC_X[i] = xs[i];
                    }
                }
                System.Threading.Thread.Sleep(100);
            }
        }
        #endregion
    }
}
